package cn.live.wechat.util;

import cn.live.wechat.constants.Constants;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * Desc:请求校验工具
 * author:lixuegang
 * Date:15/12/21
 */
@Slf4j
public class SignUtil {

    private static Logger logger = LoggerFactory.getLogger(SignUtil.class);

    /**
     * 验证签名
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] params = new String[]{Constants.TOKEN, timestamp, nonce};
        // 将token、timestamp、nonce三个参数进行字典序排序,拼接成一个字符串进行sha1加密

        String tmpStr = generateSign(sortParams(params));
        logger.debug("加密排序后的字符串：" + tmpStr);

        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信  
        return tmpStr.equals(signature.toUpperCase());
    }

    /**
     * 参数排序
     *
     * @param params
     * @return
     */
    private static String sortParams(String[] params) {
        Arrays.sort(params);
        StringBuilder result = new StringBuilder();
        for (String param : params) {
            result.append(param);
        }
        return result.toString();
    }

    /**
     * sha1加密
     *
     * @param toVerify
     * @return
     */
    private static String generateSign(String toVerify) {
        return Hashing.sha1().newHasher(16)
                .putString(toVerify, Charsets.UTF_8).hash().toString().toUpperCase();
    }

}  

